package com.xnx3.banmahuishou.agency.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ObjectUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xnx3.BaseVO;
import com.xnx3.DateUtil;
import com.xnx3.Lang;
import com.xnx3.banmahuishou.agency.vo.QishouListVO;
import com.xnx3.banmahuishou.agency.vo.QishouShowVO;
import com.xnx3.banmahuishou.agency.vo.WanggeListVO;
import com.xnx3.banmahuishou.core.entity.Agency;
import com.xnx3.banmahuishou.core.entity.Qishou;
import com.xnx3.banmahuishou.core.entity.Wangge;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.LanguageUtil;
import com.xnx3.j2ee.util.Page;
import com.xnx3.j2ee.util.Sql;
import com.xnx3.wangmarket.shop.core.entity.Order;

/**
 * 网格管理
 * @author 王晓龙
 */
@Controller(value="BanmahuishouAgencyWanggeController")
@RequestMapping("/agency/wangge/")
public class WanggeController extends BaseController  {
	@Resource
	private SqlService sqlService;
	@Resource
	private UserService userService;

	/**
	 * 网格列表
	 */
	@RequestMapping("list${url.suffix}")
	public String list(HttpServletRequest request,Model model){
		Sql sql = new Sql(request);
		sql.setSearchColumn(new String[]{"name"});
		sql.appendWhere("dailishang_userid = "+ getUserId() + " AND state = " + Wangge.STATE_NORMAL);
		int count = sqlService.count("laji_wangge", sql.getWhere());
		Page page = new Page(count, 15, request);
		sql.setSelectFromAndPage("SELECT * FROM laji_wangge", page);
		sql.setDefaultOrderBy("laji_wangge.id DESC");
		List<Wangge> list = sqlService.findBySql(sql, Wangge.class);

		ActionLogUtil.insert(request, "网格管理", "第"+page.getCurrentPageNumber()+"页");

		model.addAttribute("page", page);
		model.addAttribute("list", list);
		return "/agency/wangge/list";
	}

	/**
	 * 新增/修改网格
	 * @param id 要修改的id 。 如果是新增，这里传入0或者不传
	 */
	@RequestMapping("edit${url.suffix}")
	public String edit(
			@RequestParam(value = "id", required = false, defaultValue="0") int id,
			Model model, HttpServletRequest request){
		Wangge entity;

		if(id < 1){
			//新增
			entity = new Wangge();
			ActionLogUtil.insert(request, "进入网格新增页面");
		}else{
			//修改
			entity = sqlService.findById(Wangge.class, id);
			if(entity == null){
				return error(model, "要修改的网格不存在");
			}
			ActionLogUtil.insert(request, "进入修改网格页面", entity.toString());
		}
		//查询当前登录的用户信息
		User user = sqlService.findById(User.class, getUserId());
		//编辑页面
		model.addAttribute("nickname",user.getNickname());
		model.addAttribute("entity", entity);
		return "/agency/wangge/edit";
	}

	/**
	 * 新增、修改的网格信息进行保存
	 */
	@RequestMapping(value="save.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO variableSave(Wangge inputEntity, HttpServletRequest request){
		Wangge entity = null;			
		
		if(!StringUtils.hasLength(inputEntity.getName())) {
			return error("请输入网格名称");
		}
		if(!StringUtils.hasLength(inputEntity.getUsername())) {
			return error("请输入负责人");
		}
		if(!StringUtils.hasLength(inputEntity.getPhone())) {
			return error("请输入手机号");
		}
		
		if(inputEntity.getId() == null || inputEntity.getId() < 1){
			//新增
			entity = new Wangge();
			// 判断手机号是否合法
			if(!isMobiPhoneNum(inputEntity.getPhone())) {
				return error("手机号不合法");
			}
			//新增一个网格用户
			User user = new User();
			user.setUsername("wangge" + inputEntity.getPhone());
			user.setPassword(Lang.uuid());
			user.setNickname(inputEntity.getName());
			user.setPhone(inputEntity.getPhone());
			user.setHead("http://cdn.banxma.com/file/images/a63f71f4eea14157975b6fee1a188cb1.png");
			user.setAuthority("12");
			user.setRegtime(DateUtil.timeForUnix10());
			user.setAllSellWgight(0);
			user.setAllOrderNumbe(0);
			user.setAllIncomeMone(0);
			user.setMoney(0);
			user.setFreezemoney(0);
			BaseVO createUserVO = userService.createUser(user, request);
			if(createUserVO.getResult() - BaseVO.FAILURE == 0){
				return error(createUserVO.getInfo());
			}
			entity.setId(Lang.stringToInt(createUserVO.getInfo(), 0));
			ActionLogUtil.insertUpdateDatabase(request, user.getId(), "保存网格信息", user.toString());
			//因为是新增，所以要加上新增时间
			entity.setAddtime(DateUtil.timeForUnix10());	
		}else{
			//修改
			entity = sqlService.findById(Wangge.class, inputEntity.getId());
			if(entity == null){
				return error("要修改的目标不存在");
			}
			// 修改之前先判断传入的手机号是否已有 后台 用户在使用
			if(inputEntity.getPhone() != null && inputEntity.getPhone().length() > 0){
				if(findByPhone(inputEntity.getPhone(),entity.getId()) != null){
					return BaseVO.failure(LanguageUtil.show("user_regFailureForPhoneAlreadyExist"));
				}
			}
			// 判断手机号是否合法
			if(!isMobiPhoneNum(inputEntity.getPhone())) {
				return error("手机号不合法");
			}
			User user = sqlService.findById(User.class, inputEntity.getId());
			user.setPhone(inputEntity.getPhone());
			user.setNickname(inputEntity.getName());
			user.setUsername("wangge" + inputEntity.getPhone());
			sqlService.save(user);
		}
		//查询当前登录的用户信息
		User user = sqlService.findById(User.class, getUserId());
		//保存
		entity.setName(inputEntity.getName());
		entity.setUsername(inputEntity.getUsername());
		entity.setPhone(inputEntity.getPhone());
		entity.setState(Wangge.STATE_NORMAL);
		entity.setDailishangUserid(user.getId());
		entity.setDailishangUsername(user.getNickname());
		entity.setMoney(0);
		entity.setQishouNum(0);
		sqlService.save(entity);

		ActionLogUtil.insertUpdateDatabase(request, entity.getId(), "保存网格信息", entity.toString());
		return success();
	}

	/**
	 * 删除网格信息
	 */
	@RequestMapping(value="delete.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO delete(@RequestParam(value = "id", required = false, defaultValue="0") int id, HttpServletRequest request){
		Wangge entity = sqlService.findById(Wangge.class, id);
		if(entity == null){
			return error("要删除的目标不存在");
		}

		String sql = "SELECT * FROM laji_qishou WHERE wangge_userid = " + id;
		List<Qishou> list = sqlService.findBySqlQuery(sql, Qishou.class);
		if(list.isEmpty() && list.size()==0) {
			BaseVO baseVO = new BaseVO();
			baseVO = userService.freezeUser(id);
			entity.setState(Wangge.STATE_FROZEN);
			sqlService.save(entity);
			ActionLogUtil.insertUpdateDatabase(request, id, "代理商后台-冻结网格", "冻结了网格："+entity.toString());
			if(baseVO.getResult() == BaseVO.SUCCESS){
				return success("操作成功！");
			}else{
				return error("操作失败！");
			}
		}else {
			return error("您的下级有骑手,不能删除");
		}
	}
	/**
	 * 查看电子围栏
	 * @param id	网格用户id
	 * @param dailishangUserid 代理商id
	 * @author zxy
	 */
	@RequestMapping(value = "lookdz${url.suffix}")
	public String lookdz(HttpServletRequest request,Model model,
			@RequestParam(value = "id", required = true, defaultValue = "") int id ,
			@RequestParam(value = "dailishangUserid", required = true, defaultValue = "") int dailishangUserid) {
		//根据代理商的id 找到该代理商代理的区域
		String sql = "SELECT * FROM laji_agency WHERE userid = " + dailishangUserid;
		List<Agency> list = sqlService.findBySqlQuery(sql, Agency.class);
		StringBuffer stb = new StringBuffer();
		for (Agency agency : list) {
			// 判断该代理商的代理区域 省代理
			if (ObjectUtils.equals(agency.getShi(), "全部")) {
				stb.append(agency.getSheng() + ",");
			}
			//区代理
			if (!ObjectUtils.equals(agency.getQu(), "全部")) {
				stb.append(agency.getQu() + ",");
			}
			//市代理
			if (ObjectUtils.equals(agency.getQu(), "全部") && !ObjectUtils.equals(agency.getShi(), "全部")) {
				stb.append(agency.getShi() + ",");
			}
			String area = null;
			if ( stb.length() > 1) {
				area = stb.substring( 0 , stb.length() - 1 );
			}
			model.addAttribute( "area" , area );	
		}
		//根据代理商id 获取当前区域的坐标（获取当前区域是为了区分颜色显示）
		Wangge wangge = sqlService.findById(Wangge.class, id);
		StringBuffer stu = new StringBuffer();
		if (wangge.getServiceArea() != null) {
			String wanggechuli = wangge.getServiceArea().replace( "}" , "]").replace( "{" , "[");
			stu.append( wanggechuli + "," );
		}
		if ( stu.length() > 1) {
			String pathdq = "[" + stu.substring( 0 , stu.length() - 1 ) + "]" ;
			model.addAttribute( "pathdq" , pathdq );
		}
		//获取当前用户的网格名称
		if(wangge.getName() != null) {
			model.addAttribute("name" , wangge.getName());
		}
		//获取当前网格的骑手数量
		if (wangge.getQishouNum() != null) {
			model.addAttribute("qishouNum", wangge.getQishouNum());
		}
		model.addAttribute("id" , id );
		//日志记录
		ActionLogUtil.insert( request , "代理商后台-网格管理" + "查看电子围栏" );
		//电子围栏展示页面
		return "/agency/wangge/lookdz";
	}
	
	/**
	 * 获取当前用户代理区域下电子网格的数据
	 * @author zxy
	 * @return 电子网格数据
	 */
	@ResponseBody
	@RequestMapping(value = "getWanggeList.json",method = {RequestMethod.POST})
	public WanggeListVO getWanggeList(HttpServletRequest request,Model model) {
		WanggeListVO vo = new WanggeListVO();
		int dailishangUserid = getUserId();	//要查看的代理商的userid
		String id = request.getParameter("id");
		//获取除了当前被查看的网格 其他的网格 (为了区分被查看当前网格跟其他网格的颜色)
		String sql = "SELECT * FROM laji_wangge WHERE dailishang_userid = " + dailishangUserid + " AND id != " + id + " AND state = " + Wangge.STATE_NORMAL ;
		List<Wangge> list = sqlService.findBySqlQuery( sql, Wangge.class);
		vo.setList(list); 
		//日志记录
		ActionLogUtil.insert( request , "id为" + dailishangUserid + "的代理商查看了代理区域下的电子网格数据" );
		return vo;
	}
	/**
	 * 获取当前用户代理区域下电子网格的所有骑手数据
	 * @author zxy
	 * @return 电子网格数据
	 */
	@ResponseBody
	@RequestMapping(value = "getQishouList.json",method = {RequestMethod.POST})
	public QishouListVO getQishouList(HttpServletRequest request,Model model) {
		QishouListVO vo = new QishouListVO();
		List<QishouShowVO> showList = new ArrayList<QishouShowVO>();
		int dailishangUserid = getUserId();	//要查看的代理商的userid
		//取出当前代理商下的工作状态正常的骑手集合
		String sql = "SELECT * FROM laji_qishou WHERE dailishang_userid = " + dailishangUserid + " AND state = " + Qishou.STATE_NORMAL ;
		List<Qishou> list = sqlService.findBySqlQuery( sql, Qishou.class);
		if (!list.isEmpty()) {
			for (Qishou qishou : list) {
				QishouShowVO showvo = new QishouShowVO();
				showvo.setLatitude(qishou.getLatitude());
				showvo.setLongitude(qishou.getLongitude());
				showvo.setQishouid(qishou.getId());
				int count = sqlService.count("shop_order", " WHERE qishou_id = " + qishou.getId() +  " AND state = " + Order.STATE_DAIQUHUO + " AND reserve_end_time >= " + DateUtil.timeForUnix10());
				showvo.setCount(count);
				showvo.setQishouName(qishou.getName());
				showvo.setWanggeName(qishou.getWanggeUsername());
				showList.add(showvo);
			}
		}
		vo.setList(showList); 
		//日志记录
		ActionLogUtil.insert( request , "id为" + dailishangUserid + "的代理商查看了代理区域下骑手数据" );
		return vo;
	}
	
	/**
	 * 分配电子围栏
	 * @param id 网格id
	 * @param dailishangUserid 代理商用户id
	 * @author zxy
	 */
	@RequestMapping(value = "distribute${url.suffix}")
	public String distribute(HttpServletRequest request,Model model,
			@RequestParam(value = "id", required = true, defaultValue = "") int id ,
			@RequestParam(value = "dailishangUserid", required = true, defaultValue = "") int dailishangUserid ) {
		//根据代理商的id 找到该代理商代理的区域
		String sql = "SELECT * FROM laji_agency WHERE userid = " + dailishangUserid;
		List<Agency> list = sqlService.findBySqlQuery(sql, Agency.class);
		StringBuffer stb = new StringBuffer();
		for (Agency agency : list) {
			// 判断该代理商的代理区域 省代理
			if (ObjectUtils.equals(agency.getShi(), "全部")) {
				stb.append(agency.getSheng() + ",");
			}
			//区代理
			if (!ObjectUtils.equals(agency.getQu(), "全部")) {
				stb.append(agency.getQu() + ",");
			}
			//市代理
			if (ObjectUtils.equals(agency.getQu(), "全部") && !ObjectUtils.equals(agency.getShi(), "全部")) {
				stb.append(agency.getShi() + ",");
			}
			String area = null;
			if ( stb.length() > 1) {
				area = stb.substring( 0 , stb.length() - 1 );
			}
			model.addAttribute( "area" , area );	
		}
		//根据代理商的id 获取该代理商底下除了当前网格其他已经分配的网格坐标集合
		String sqlqita = "SELECT * FROM laji_wangge WHERE dailishang_userid = " + dailishangUserid  + " AND id <> " + id + " AND state = " + Wangge.STATE_NORMAL;
		List<Wangge> listqita = sqlService.findBySqlQuery( sqlqita , Wangge.class );
		StringBuffer str = new StringBuffer();
		for (Wangge wangge : listqita) {
			if (wangge.getServiceArea() != null) {
				String wanggechuli = wangge.getServiceArea().replace( "}" , "]").replace( "{" , "[");
				str.append( wanggechuli + "," );
			}
		}
		if(str.length() > 1) {
			String pathqt = "[" + str.substring( 0 , str.length() - 1 ) + "]";
			model.addAttribute( "pathqt" , pathqt );
		}
		//根据代理商id 获取当前区域的坐标
		Wangge wangge = sqlService.findById(Wangge.class, id);
		StringBuffer stu = new StringBuffer();
		if (wangge.getServiceArea() != null) {
			String zuobiaochuli = wangge.getServiceArea().replace( "}" , "]").replace( "{" , "[");
			stu.append( zuobiaochuli + "," );
		}
		if ( stu.length() > 1) {
			String pathdq = "[" + stu.substring( 0 , stu.length() - 1 ) + "]" ;
			model.addAttribute( "pathdq" , pathdq );
		}
		model.addAttribute("id" , id );
		model.addAttribute("ishaveWangge", wangge.getServiceArea() != null && wangge.getServiceArea().length() > 7);	//当前是否有网格，true 有
		//日志记录
		ActionLogUtil.insert( request , "代理商后台-网格管理" + "分配电子围栏" );
		//电子围栏分配页面
		return "/agency/wangge/distribute";
	}


	/**
	 * 保存电子围栏
	 * @param id 当前网格id
	 * @param all 前台传来的地址
	 * @author zxy
	 */
	@RequestMapping(value = "saveAll.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO areaSave(HttpServletRequest request,Model model,
			@RequestParam(value = "all", required = false, defaultValue="") String all,
			@RequestParam(value = "id", required = true, defaultValue="0") int id){
		// all格式 [{"lon":118.818171,"lat":36.454356},{"lon":119.142268,"lat":36.454356},{"lon":118.897822,"lat":36.31948}]
		String zuobiao = all.toString().replace( "\"lon\":" , "" ).replace( "\"lat\":" , "" );
		Wangge entity = sqlService.findById(Wangge.class, id);
		entity.setServiceArea(zuobiao);
		model.addAttribute( "path" , zuobiao );
		sqlService.save(entity);
		//日志记录
		ActionLogUtil.insertUpdateDatabase(request, entity.getId(), "保存电子围栏", entity.toString());
		return success();
	}
}
